package servlet.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import pojo.MerchantApplication;
import service.MerchantApplicationManager;
import service.impl.MerchantApplicationManagerImpl;
import servlet.LoadAllMerchantServlet;
import util.JsonUtil;
import dto.AdminMerchantDto;
import dto.ResponseDto;

public class GetAllMerchantServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantApplicationManager aManager = null;
	Logger logger = LogManager.getLogger(LoadAllMerchantServlet.class);
	
    public GetAllMerchantServlet() {
        super();
        aManager = new MerchantApplicationManagerImpl();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<MerchantApplication> merchants = aManager.getAll();
		List<AdminMerchantDto> adminMerchantDtos = new ArrayList<>();
		String avatarPath = (String) getServletContext().getAttribute("imagepath");
		String idCardPath = getServletContext().getContextPath()+"/merchant/info/idcard?name=";
		for (MerchantApplication application : merchants) {
			AdminMerchantDto adminMerchantDto = new AdminMerchantDto(application.getName(),idCardPath+application.getName(),
					avatarPath+application.getAvatar(),application.getAddress(),application.getStatus());
			adminMerchantDtos.add(adminMerchantDto);
		}
		ResponseDto responseDto = new ResponseDto(1,"success",adminMerchantDtos);
		PrintWriter writer = response.getWriter();
		writer.write(JsonUtil.toJsonString(responseDto));
		writer.close();
	}

}
